﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.U2D.Sprites;
using UnityEngine;

namespace Game.Editor
{
    public class PlayerSpritePostprocessor : AssetPostprocessor
    {
        private static readonly string _PathPattern = @"(Assets/Game/Assets/Players/\d+/)(\d+).png";
        private static readonly string _ControllerAssetPath =
            "Assets/Game/Assets/Players/Template/Animations/PlayerTemplateAnimator.controller";
        private static List<string> _toProcessPathList = new List<string>();
        
        private void OnPostprocessTexture(Texture2D texture)
        {
            MatchCollection matchCollection = Regex.Matches(assetPath, _PathPattern);
            if (matchCollection.Count > 0)
            {
                TextureImporter textureImporter = (TextureImporter) assetImporter;
                if (textureImporter.textureType == TextureImporterType.Sprite)
                {
                    return;
                }
                textureImporter.textureType = TextureImporterType.Sprite;
                _toProcessPathList.Add(assetPath);
                assetImporter.SaveAndReimport();
            }
        }

        private void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
        {
            if (!_toProcessPathList.Contains(assetPath))
            {
                return;
            }
            _toProcessPathList.Remove(assetPath);
            PetSpritePostprocessor.PostprocessBoneSprite(assetPath, _PathPattern, _ControllerAssetPath, assetImporter, sprites[0]);
        }
    }
}